<script setup name="SysDeptIndex">
import eventBus from "@/utils/eventBus";
import { usePagination } from "@/utils/composables";
import FormMode from "./modules/FormMode/index.vue";
import { parseTime } from "@/utils/aidex";
import {
  listRubbishType,
  delBizRubbishType,
  listRubbishTypeTree
} from "@/api/biz/bizRubbishType";
const { pagination, getParams, onSizeChange, onCurrentChange, onSortChange } =
  usePagination();
const router = useRouter();

const data = ref({
  loading: false,
  /**
   * 详情展示模式
   * router 路由跳转
   * dialog 对话框
   * drawer 抽屉
   */
  formMode: "drawer",
  // 详情
  formModeProps: {
    visible: false,
    id: ""
  },
  // 搜索
  search: {
    name: "",
    deptId: "",
    busType: "0"
  },
  // 批量操作
  batch: {
    enable: false,
    selectionDataList: []
  },
  // 列表数据
  dataList: [],
  colorList: ["#F38709", "#813AFD", "#00C4AA", "#4B7AEE"],
  // 部门树 列表
  deptOptions: [],
  expandedKeys: []
});

// 页面挂载时 调用
onMounted(() => {
  getDataList();
  if (data.value.formMode === "router") {
    eventBus.on("get-data-list", () => {
      getDataList();
    });
  }
  // 获取部门树
  // getTreeselect();
});
//
onBeforeUnmount(() => {
  if (data.value.formMode === "router") {
    eventBus.off("get-data-list");
  }
});
// 选取随机颜色
function getRandomColor(index) {
  return data.value.colorList[index % 4];
}
// 截取用户名称
function getShowName(name) {
  if (name.length > 2) {
    name = name.substring(name.length - 2);
  }
  return name;
}
// 部门树
function getTreeselect() {
  listRubbishTypeTree("0", 3).then((response) => {
    data.value.deptOptions = response.data;
    getExpandedKeys(data.value.deptOptions, 3);
  });
}
function getExpandedKeys(nodes, expandLevel) {
  if (expandLevel > 1) {
    // 最后一层不展开
    if (nodes != null) {
      nodes.forEach((node) => {
        data.value.expandedKeys.push(node.id);
        expandLevel = expandLevel - 1;
        return getExpandedKeys(node.children, expandLevel);
      });
    }
  }
}
function getDataList() {
  data.value.loading = true;
  let params = getParams();
  data.value.search.deptName && (params.name = data.value.search.deptName);
  data.value.search.busType && (params.busType = data.value.search.busType);
  console.log("params", params);
  listRubbishType(params, "", 3).then((res) => {
    data.value.loading = false;
    data.value.dataList = res.data;
    // pagination.value.total = res.data.total;
  });
}

// 每页数量切换
function sizeChange(size) {
  onSizeChange(size).then(() => getDataList());
}

// 当前页码切换（翻页）
function currentChange(page = 1) {
  onCurrentChange(page).then(() => getDataList());
}

// 字段排序
function sortChange(prop, order) {
  onSortChange(prop, order).then(() => getDataList());
}
//  获取树选项节点
function getnode(node, prop, event) {
  console.log("node", node, prop, event);
  data.value.search.deptId = node.id;
}
function onCreate() {
  if (data.value.formMode === "router") {
    router.push({
      name: "routerName"
    });
  } else {
    data.value.formModeProps.id = "";
    data.value.formModeProps.visible = true;
  }
}

function onEdit(row) {
  data.value.formMode = "drawer";
  if (data.value.formMode === "router") {
    router.push({
      name: "routerName",
      params: {
        id: row.id
      }
    });
  } else {
    data.value.formModeProps.id = row.id;
    data.value.formModeProps.busType = row.busType;
    data.value.formModeProps.visible = true;
  }
}
function onAdd() {
  data.value.formModeProps.id = "";
  data.value.formModeProps.busType = "0";
  data.value.formMode = "dialog";
  data.value.formModeProps.visible = true;
}
// 批量删除 单独删除
function onDel(row) {
  const ids =
    row.id ||
    data.value.batch.selectionDataList.map((item) => {
      return item.id;
    });
  const names =
    row.deptName ||
    data.value.batch.selectionDataList.map((item) => {
      return item.deptName;
    });
  if (ids.length > 0) {
    ElMessageBox.confirm("确认删除「" + names + "」吗？", "确认信息")
      .then(() => {
        delBizRubbishType(ids).then((res) => {
          getDataList();
          if (res.code == 200)
            ElMessage.success({
              message: "删除成功",
              center: true
            });
        });
      })
      .catch(() => {});
  } else {
    ElMessage.warning({ message: "请选择数据", center: true });
  }
}
</script>

<template>
  <div>
    <page-main style="height: calc(100vh - 160px); margin: 10px">
      <el-row>
        <el-col :span="24" style="text-align: right">
          <el-button-group>
            <el-button type="primary" @click="onAdd">
              <template #icon>
                <el-icon>
                  <svg-icon name="ep:circle-plus" />
                </el-icon>
              </template>
              新增
            </el-button>
            <el-button type="danger" @click="onDel">
              <template #icon>
                <el-icon>
                  <svg-icon name="ep:close-bold" :size="20" />
                </el-icon>
              </template>
              删除
            </el-button>
            <el-button @click="currentChange()">
              <template #icon>
                <el-icon><svg-icon name="ep:refresh" :size="20" /></el-icon>
              </template>
              刷新
            </el-button>
          </el-button-group>
        </el-col>
      </el-row>
      <div style="height: calc(100vh - 240px); overflow-y: auto">
        <el-table
          ref="table"
          v-loading="data.loading"
          class="list-table"
          :data="data.dataList"
          border
          highlight-current-row
          row-key="id"
          :lazy="true"
          :load="load"
          @sort-change="sortChange"
          @selection-change="data.batch.selectionDataList = $event"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          >
          <el-table-column type="selection" align="center" />
          <el-table-column prop="deptName" label="分类名称">
            <template v-slot="scope">
              <svg-icon style="color: #409eff" name="ep:star"> </svg-icon>
              &nbsp;
              {{ scope.row.deptName }}
            </template>
          </el-table-column>

          <el-table-column
            prop="deptCode"
            label="分类编码"
            align="center"
            width="180"
          />

          <el-table-column prop="puras" label="状态" width="80" align="center">
            <template v-slot="scope">
              <el-tag v-if="scope.row.status == '0'" effect="Light"
                >正常</el-tag
              >
              <el-tag v-else effect="Light" type="warning">停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="puras"
            label="首页显示"
            width="120"
            align="center"
          >
            <template v-slot="scope">
              <el-tag v-if="scope.row.isIndex == 1" effect="Light">显示</el-tag>
              <el-tag v-else effect="Light" type="warning">不显示</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="treeSort"
            label="排序"
            width="70"
            align="center"
          />
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="180"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="id"
            label="分类ID"
            align="center"
            width="320"
          />
          <el-table-column label="操作" width="160" align="center">
            <template #default="scope">
              <el-button-group>
                <el-button
                  type="primary"
                  size="small"
                  text
                  @click="onEdit(scope.row)"
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ant-design:edit-filled" />
                    </el-icon>
                  </template>
                  编 辑</el-button
                >

                <el-button
                  type="danger"
                  text
                  size="small"
                  @click="onDel(scope.row)"
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ep:close-bold" />
                    </el-icon>
                  </template>
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- <el-pagination
        :current-page="pagination.page"
        :total="pagination.total"
        :page-size="pagination.size"
        :page-sizes="pagination.sizes"
        :layout="pagination.layout"
        :hide-on-single-page="false"
        class="pagination"
        background
        @size-change="sizeChange"
        @current-change="currentChange"
      /> -->
    </page-main>
    <FormMode
      v-if="['dialog', 'drawer'].includes(data.formMode)"
      :id="data.formModeProps.id"
      :busType="data.formModeProps.busType"
      v-model="data.formModeProps.visible"
      :mode="data.formMode"
      @success="getDataList"
    />
  </div>
</template>

<style lang="scss" scoped>
.el-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
